import { ConfigEnv, UserConfig } from 'vite'
// import viewport from 'postcss-mobile-forever'
import autoprefixer from 'autoprefixer'
import { join } from 'path'
import { loadEnv } from 'vite'
import { createVitePlugins } from './build/vite'
import { exclude, include } from './build/vite/optimize'

export default ({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)

  return {
    base: './',
    plugins: createVitePlugins(mode),

    server: {
      port: 3000,
      host: '0.0.0.0',
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },

    resolve: {
      alias: {
        '~@': join(__dirname, './src'),
        '@': join(__dirname, './src'),
        '~': join(__dirname, './src/assets'),
        '~root': join(__dirname, '.'),
      },
    },

    css: {
      postcss: {
        plugins: [
          autoprefixer({
            overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8'],
          }),
          // https://github.com/wswmsword/postcss-mobile-forever
          // viewport({
          //   appSelector: '#app',
          //   viewportWidth: 375,
          //   maxDisplayWidth: 600,
          //   rootContainingBlockSelectorList: [
          //     'van-tabbar',
          //     'van-popup',
          //   ],
          //   border: true,
          // }),
        ],
      },
    },

    build: {
      chunkSizeWarningLimit: 2048,
      outDir: env.VITE_APP_OUT_DIR || 'dist',
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      },
      assetsInlineLimit: 4096,
      cssCodeSplit: true,
      sourcemap: false,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },

    optimizeDeps: { include, exclude },
  }
}


